package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result.Result;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.DeletionNotAllowedException;
import com.itheima.reggie.exception.UpdateNotAllowedException;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Transactional
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 套餐的分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<SetmealDto>> setmealPage(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>()
                .like(name != null, Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, queryWrapper);

        BeanUtil.copyProperties(setmealPage, setmealDtoPage, "records");
        //这是我这一页所要显示的所有的setmeal
        List<Setmeal> records = setmealPage.getRecords();
        List<Long> setmealIds = null;
        if (records != null && !records.isEmpty()) {
            setmealIds = records.stream().map(Setmeal::getId).collect(Collectors.toList());
        }

        //获取所有的套餐分类放到一个集合中
        List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().eq(Category::getType, 2));
        //把套餐分类集合映射成key为分类id，value为分类名字的map
        Map<Long, String> map = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        //获取所有的setmealIds提及的套餐菜品，放到一个集合中
        List<SetmealDish> setmealDishList = setmealDishService.list(new LambdaQueryWrapper<SetmealDish>().in(setmealIds != null && !setmealIds.isEmpty(), SetmealDish::getSetmealId, setmealIds));
        //把套餐菜品集合映射成key为setmealid，value为setmealdish集合的map
        Map<Long, List<SetmealDish>> map2 = setmealDishList.stream().collect(Collectors.groupingBy(SetmealDish::getSetmealId));
        //把setmealdto分类名字属性CategoryName设置上了
        List<SetmealDto> setmealDtoList = records.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtil.copyProperties(setmeal, setmealDto);
            //设置对应的CategoryName
            Long setmealCategoryId = setmeal.getCategoryId();
            setmealDto.setCategoryName(map.get(setmealCategoryId));
            //设置对应的setmealdish集合
            Long setmealId = setmeal.getId();
            setmealDto.setSetmealDishes(map2.get(setmealId));
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtoList);
        return Result.success(setmealDtoPage);
    }

    /**
     * 新增套餐及包含的菜品
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    public Result<String> saveSetmeal(@RequestBody SetmealDto setmealDto) {
        setmealService.saveSetmealWithDish(setmealDto);
        return Result.success();
    }


    /**
     * 根据setmeal的id删除对应套餐，但是得注意，
     * 1.如果不是停售，不能删除
     * 2.如果他下面有对应的菜品，要一并删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> batchDeleteSetmeal(@RequestParam List<Long> ids) {
        //找出所有ids对应的套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<Setmeal>()
                .in(ids != null && !ids.isEmpty(), Setmeal::getId, ids);
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);
        for (Setmeal setmeal : setmealList) {
            if (setmeal.getStatus() == 1) {
                throw new DeletionNotAllowedException("套餐是在售状态，不能删除");
            }
        }
        setmealService.remove(setmealLambdaQueryWrapper);
        //查出对应的菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(queryWrapper);
        return Result.success();
    }

    /**
     * 批量修改套餐状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> batchUpdateSetmealStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        //找出所有ids对应的套餐
        LambdaUpdateWrapper<Setmeal> setmealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        setmealLambdaUpdateWrapper.in(ids != null && !ids.isEmpty(), Setmeal::getId, ids)
                .set(status != null, Setmeal::getStatus, status);
        setmealService.update(setmealLambdaUpdateWrapper);
        return Result.success();
    }

//    http://localhost:8080/setmeal/1781570120183742466

    /**
     * 根据id回显套餐
     *
     * @param id setmeal的id
     * @return SetmealDto
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> getById(@PathVariable Long id) {

        Setmeal setmeal = setmealService.getById(id);
        Long setmealCategoryId = setmeal.getCategoryId();
        SetmealDto setmealDto = new SetmealDto();
        BeanUtil.copyProperties(setmeal, setmealDto);
        setmealDto.setCategoryName(categoryService.getById(setmealCategoryId).getName());
        setmealDto.setSetmealDishes(setmealDishService.list(new LambdaQueryWrapper<SetmealDish>().eq(id != null, SetmealDish::getSetmealId, id)));
        return Result.success(setmealDto);
    }

    /**
     * 修改套餐
     * 先判断一下setmeal的状态，然后再修改
     *
     * @param setmealDto
     * @return
     */

    @PutMapping
    public Result<String> updateSetmealWithDish(@RequestBody SetmealDto setmealDto) {
        Long id = setmealDto.getId();
        Setmeal setmeal = setmealService.getById(id);
        Integer status = setmeal.getStatus();
        if (status == 1) {
            throw new UpdateNotAllowedException("当前套餐是起售中，不能修改");
        }
        setmealService.updateById(setmealDto);

        //根据setmeal的id删除对应的所有菜品
        setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>().eq(id != null, SetmealDish::getSetmealId, id));

        //再添加新的
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().peek(setmealDish -> setmealDish.setSetmealId(id)).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

        return Result.success();
    }

}
